package config

import (
	"bytes"
	"fmt"
	"gin.project.template/common/constant"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"os"
)

type Redis struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
	PoolSize int    `mapstructure:"pool_size"`
}

type SystemConfig struct {
	Mode        string `mapstructure:"mode"`
	Port        int    `mapstructure:"port"`
	*Zap        `mapstructure:"zap"`
	*Redis      `mapstructure:"redis"`
	MysqlDns    string
	PostgresDns string
}

var Conf = new(SystemConfig)

func InitViper() {
	var config string
	var isEnv bool

	if envConfig := os.Getenv(constant.ConfigFileKey); envConfig == "" {
		config = constant.DefaultConfigFile
		fmt.Printf("已应用系统默认配置文件%s\n", config)
	} else {
		config = envConfig
		isEnv = true
		fmt.Printf("已应用环境变量配置文件%s\n", config)
	}

	var err error
	v := viper.New()
	if isEnv {
		v.SetConfigType("json")
		yamlConfig := []byte(config)
		err = v.ReadConfig(bytes.NewBuffer(yamlConfig))
	} else {
		v.SetConfigType("yaml")
		filePath := "./" + config
		v.SetConfigFile(filePath)
		err = v.ReadInConfig()
	}

	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.Name)
		if err = v.Unmarshal(&Conf); err != nil {
			fmt.Println("Unmarshal err:", err)
		}
	})

	if err := v.Unmarshal(&Conf); err != nil {
		fmt.Println(err)
	}
	return
}
